#include "../include/head.h"
#include "../include/func.h"

#define LOGIN_TRAIN_LENGTH ((sizeof(int)) + (sizeof(CmdType)) + (sizeof(User_t)) + (login_train.len))

int login_client(int sockfd, User_t *user) {
    // 初始化
    char username[64] = {0};
    printf("\033[1;97m请输入您的用户名: \033[0m");
    scanf("%s", username);

    // strcpy(user->userName, username);
    // strcpy(user->salt, "salt");
    // strcpy(user->cryptpasswd, "cryptpasswd");
    // strcpy(user->pwd, "pwd");
    *user = (User_t){
        .userName = username,
        .salt = "salt",
        .cryptpasswd = "cryptpasswd",
        .pwd = "pwd"
    };

    // 发送小火车
    train_t login_train = {
        .len = 0,
        .type = CMD_TYPE_LOGIN_USRNAME,
        .user = *user
    };
    send(sockfd, &login_train, LOGIN_TRAIN_LENGTH , 0);

    int len = 0;
    recv(sockfd, &len, sizeof(len), MSG_WAITALL);
    CmdType cmdType;
    recv(sockfd, &cmdType, sizeof(CmdType), MSG_WAITALL);
    recv(sockfd, user, sizeof(user), MSG_WAITALL);

    if (cmdType == MSG_TYPE_LOGIN_SALT) {
        char password[64] = {0};
        printf("\033[1;97m请输入您的mima: \033[0m");
        scanf("%s", password);
        // 用盐值加密
        char encrypted_password[65] = {0};
        encrypt_password(password, user->salt, encrypt_password);

        // 填充小火车
        login_train = (train_t){
            .len = 0,
            .type = CMD_TYPE_REGISTER_ENCRYTPTEDCODE,
            .user = *user,
        };
        strcpy(login_train.user.cryptpasswd, encrypted_password);
        send(sockfd, &login_train, LOGIN_TRAIN_LENGTH, 0);

        int len = 0;
        recv(sockfd, &len, sizeof(len), MSG_WAITALL);
        CmdType cmdType;
        recv(sockfd, &cmdType, sizeof(CmdType), MSG_WAITALL);
        recv(sockfd, user, sizeof(user), MSG_WAITALL);

        if (cmdType == MSG_TYPE_LOGINOK) {
            printf("\n\033[1;96m正在登录中请稍等。。。。。\033[0m\n");
            sleep(5);
            printf("\033[1;96m------------------------------------\033[0m \n");
            printf("\033[1;96m密码正确！\033[0m\n");
            return 0;
        } else {
            printf("\033[1;96m------------------------------------\033[0m \n");
            printf("\033[1;96m密码错误！\033[0m\n");
            return -1;
        } 
    } else {
        printf("\033[1;96m------------------------------------\033[0m \n");
        printf("\033[1;96m用户名不存在！\033[0m\n");
        return -1;
    }

    return 0;
}
